<template>
  <div class="tabbar">
    <ul>
      <li 
        v-for="(item, index) of routerList" 
        :key="index"
        @click="switchTab(item.path)"
      >
        <img :src="isSelected(item.path) ? item.selected : item.active" />
        <span :class="isSelected(item.path) ? 'active' : ''">{{ item.title }}</span>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { reactive, getCurrentInstance } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const { proxy } = getCurrentInstance()

const routerList = reactive([
  {
    title: '首页',
    path: '/home',
    active: proxy.baseUrl + '/img/tabbar/home.png',
    selected: proxy.baseUrl + '/img/tabbar/home-select.png'
  },
  {
    title: '分类',
    path: '/list',
    active: proxy.baseUrl + '/img/tabbar/list.png',
    selected: proxy.baseUrl + '/img/tabbar/list-select.png'
  },
  {
    title: '购物车',
    path: '/cart',
    active: proxy.baseUrl + '/img/tabbar/cart.png',
    selected: proxy.baseUrl + '/img/tabbar/cart-select.png'
  },
  {
    title: '我的',
    path: '/my',
    active: proxy.baseUrl + '/img/tabbar/my.png',
    selected: proxy.baseUrl + '/img/tabbar/my-select.png'
  }
])

const router = useRouter()
const route = useRoute()
function switchTab(path) {
  if (route.path == path) return
  router.push(path)
}

const isSelected = path => {
  let reg = new RegExp(`^${path}/?$`)
  return reg.test(route.path)
}

</script>

<style lang="less" scoped>
.tabbar {
  width: 100vw;
  height: 50px;
  background-color: #fff;

  ul {
    display: flex;
    justify-content: space-around;
    align-items: center;
    width: 100%;
    height: 100%;

    li {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      img {
        width: 26px;
	      height: 26px;
      }

      span {
        font-size: 16px;
      }

      .active {
        color:red;
      }
    }
  }
}
</style>